package com.gugu.procedure.service;


import com.gugu.procedure.bean.ProductionRecord;
import com.gugu.procedure.bean.Staff;
import com.gugu.procedure.bean.WorkDone;
import com.gugu.procedure.common.Constant;
import com.gugu.procedure.common.MessageResult;
import com.gugu.procedure.dao.WorkDoneDao;
import com.gugu.procedure.exceptions.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.List;

@Service
public class WorkDoneService {

    @Autowired
    private WorkDoneDao workDoneDao;
    @Autowired
    private StaffService staffService;
    @Autowired
    private ProductionRecordService productionRecordService;

    public WorkDone findById(Long id) {
        return workDoneDao.findById(id).get();
    }


    @Transactional
    public MessageResult save(WorkDone workDone) {
        WorkDone bean = workDoneDao.findTopByOrderNoAndSpecsAndNumber1AndNumber2(workDone.getOrderNo(), workDone.getSpecs(), workDone.getNumber1(), workDone.getNumber2());
        if (bean != null) {
            delete(bean.getId());
        }
        workDone = workDoneDao.saveAndFlush(workDone);
        List<ProductionRecord> productionRecords = productionRecordService.listWorkDoneProductionRecord(workDone.getOrderNo(), workDone.getSpecs(), workDone.getWorkmanship(), workDone.getNumber1());
        if (Integer.parseInt(workDone.getAmount2()) > productionRecords.size()) {
            throw new BusinessException("订单号" + workDone.getOrderNo() + "规格" + workDone.getSpecs() + "工序"
                    + workDone.getWorkmanship() + "工号" + workDone.getNumber1() + "记录数据异常，完成数量" + productionRecords.size()
                    + "小于分配数量" + workDone.getAmount2());
        }
        int num = Integer.parseInt(workDone.getAmount2());
        int recordNum = productionRecords.size();
        Staff staff = staffService.findByStaffNumber(workDone.getNumber2());
        for (int k = recordNum - 1; k >= (recordNum - num); k--) {
            ProductionRecord productionRecord = productionRecords.get(k);
            productionRecord.setWorkDoneFlag(Constant.WORK_DONE_FLAG_Y);
            productionRecord.setStaffName(staff.getName());
            productionRecord.setWorkDoneId(workDone.getId());
            productionRecord.setStaffNumber(staff.getNumber());
            productionRecord.setStaffId(staff.getId());
            productionRecordService.update(productionRecord);
        }
        return MessageResult.success();
    }

    @Transactional
    public MessageResult saveAll(List<WorkDone> list) {
        for (WorkDone workDone : list) {
            String number1 = workDone.getNumber1();
            String orderNo = workDone.getOrderNo();
            String specs = workDone.getSpecs();
            String workmanship = workDone.getWorkmanship();
            Staff staff = staffService.findByStaffNumber(number1);
            if (staff == null) {
                throw new BusinessException("请检查工号" + number1 + "是否存在");
            }
            save(workDone);
        }
        return MessageResult.success();
    }

    @Transactional
    public MessageResult delete(Long id) {
        WorkDone workDone = findById(id);
        // 将修改的ProductionRecord记录还原回来
        List<ProductionRecord> list = productionRecordService.findByWorkDoneId(workDone.getId());
        Staff staff = staffService.findByStaffNumber(workDone.getNumber1());
        for (ProductionRecord productionRecord : list) {
            productionRecord.setStaffId(staff.getId());
            productionRecord.setStaffNumber(staff.getNumber());
            productionRecord.setStaffName(staff.getName());
            productionRecord.setWorkDoneFlag(Constant.WORK_DONE_FLAG_N);
            productionRecordService.update(productionRecord);
        }
        workDoneDao.deleteById(id);
        return MessageResult.success();
    }

    public MessageResult page(String orderNo, String account, int pageNo, int pageSize) {
        Specification<WorkDone> spec = (Specification<WorkDone>) (root, query, cb) -> {
            List<Predicate> list = new ArrayList<>();
            if (StringUtils.hasText(orderNo)) {
                list.add(cb.equal(root.get("orderNo").as(String.class), orderNo));
            }

            if (StringUtils.hasText(account)) {
                Predicate pre = cb.equal(root.get("number1").as(String.class), account);
                pre = cb.or(pre, (cb.equal(root.get("number2").as(String.class), account)));
                list.add(pre);
            }
            Predicate[] pre = new Predicate[list.size()];
            query.where(list.toArray(pre));
            return query.getRestriction();
        };
        PageRequest pr = PageRequest.of(pageNo - 1, pageSize, Sort.Direction.DESC, "createTime");
        Page<WorkDone> recordsPage = workDoneDao.findAll(spec, pr);
        MessageResult mr = MessageResult.success();
        mr.setTotal(recordsPage.getTotalElements());
        mr.setTotalElement(recordsPage.getContent());
        return mr;
    }


}
